package com.itheima.search.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.search.domain.News;
import com.itheima.search.domain.NewsVO;
import com.itheima.search.mapper.NewsMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@SuppressWarnings("all")
public class EsSyncService {

    @Autowired
    private RestHighLevelClient esClient;

    @Autowired
    private NewsMapper newsMapper;

    private static final String INDEX_NAME = "news_index";
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将所有数据库中的新闻同步到 ES
     */
    public void syncAllNewsToEs() throws IOException {
        List<NewsVO> newsList = newsMapper.selectAllWithTypeName();

        for (NewsVO news : newsList) {
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("newsId", news.getNewsId())
                    .field("title", news.getTitle())
                    .field("source", news.getSource())
                    .field("newsType", news.getNewsType())  // 使用 type_name
                    .field("content", news.getContent())
                    .field("status", news.getStatus())
                    .field("createTime", news.getCreateTime())
                    .endObject();

            IndexRequest request = new IndexRequest(INDEX_NAME)
                    .id(news.getNewsId().toString())
                    .source(builder);

            esClient.index(request, RequestOptions.DEFAULT);
        }
    }


    /**
     * 同步单条新闻到 ES
     */
    public void syncOneNewsToEs(String newsId) throws IOException {
        NewsVO news = newsMapper.selectOneWithTypeName(newsId);
        if (news != null) {
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("newsId", news.getNewsId())
                    .field("title", news.getTitle())
                    .field("source", news.getSource())
                    .field("newsType", news.getNewsType())
                    .field("content", news.getContent())
                    .field("status", news.getStatus())
                    .field("createTime", news.getCreateTime())
                    .endObject();

            IndexRequest request = new IndexRequest(INDEX_NAME)
                    .id(news.getNewsId().toString())
                    .source(builder);

            esClient.index(request, RequestOptions.DEFAULT);
        }
    }
}
